<template>
  <div>
    <p class="title">编辑图书</p>
    <el-form ref="formRef" :model="form" label-width="120px">
      <el-form-item label="图书名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="图书定价">
        <el-input v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="出版单位">
        <el-input v-model="form.publisher"></el-input>
      </el-form-item>
      <el-form-item label="出版时间">
        <el-date-picker v-model="form.pubDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
      </el-form-item>
      <el-form-item label="图书作者">
        <el-input v-model="form.author"></el-input>
      </el-form-item>
    </el-form>
    <el-row justify="end">
      <el-col :span="4" >
        <el-button type="primary" @click="update">确定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
    name: 'BookEdit' 
}
</script>

<script setup>
import { getCurrentInstance , onBeforeMount , reactive } from 'vue' ;
import { useRouter , useRoute } from 'vue-router' ;

// 获得Router对象 ( 相当于 this.$router )
const router = useRouter();
// 获得当前路由 ( 相当于 this.$route )
const route = useRoute();

const { proxy } = getCurrentInstance();

const form = reactive({
          name: '' ,
          price: '' ,
          publisher: '' ,
          pubDate: '' ,
          author: '' 
        });

// 生命周期钩子
onBeforeMount( async () =>{
  // 获得路由参数
  let id = route.params.id ;
  let resp = await proxy.$http.get( `/book/find/${id}` );
  if( resp.status == 200 ) {
    if( resp.data.success ) {
      Object.assign( form , resp.data.book );
      return ;
    }
    // 编程式导航
    router.push( { name: 'bookList' } );
  }
  console.log( resp.data );
});

function update(){
  proxy.$http.post( '/book/update' , form ).then( resp=>{
    
    if( resp.status == 200 ) {
      alert( resp.data.message );
      if( resp.data.success ) {
        // 编程式导航
        router.push( { name: 'bookList' } );
      }
    }
  }).catch( error => {
    console.log( error );
  });
}

</script>

<style scoped>
.title {
  text-align: center ;
  font-weight: bold ;
  letter-spacing: 0.5em ;
}
</style>